package com.example.demowebsocket.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demowebsocket.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

@Component
public class ReceiverRedisMessage {
    private static final Logger log = LoggerFactory.getLogger(ReceiverRedisMessage.class);

    @Autowired
    private CountDownLatch latch;

    /**
     * https://www.jb51.net/article/185534.htm
     * 队列消息接收方法
     *
     * @param jsonMsg
     */
    public void receiveMessage(String jsonMsg) {
        log.info("[开始消费REDIS消息队列phone数据...]");
        try {
            log.info("监听者收到消息：{}", jsonMsg);
            Object parse = JSON.parse(jsonMsg); // 设置接受的json可以去除转义符
            User user = JSONObject.parseObject(parse.toString(), User.class);
            log.info("[消费REDIS消息队列phone数据成功.] 对象转换后：" + user.toString());
            // 单发
            // WebSocketServer.sendInfo(user.toString(), "10");
            
            // 群发
            WebSocketServer.sendInfoQF(user.toString());
        } catch (Exception e) {
            log.error("[消费REDIS消息队列phone数据失败，失败信息:{}]", e.getMessage());
        }
        latch.countDown();
    }

}
